package com.framework.service.impl;

import com.baomidou.mybatisplus.service.impl.ServiceImpl;
import com.framework.dao.DeptSmsDao;
import com.framework.entity.sys.SysAgent;
import com.framework.entity.sys.SysDeptSms;
import com.framework.entity.sys.SysDeptSmsInfo;
import com.framework.entity.sys.SysDict;
import com.framework.entity.ter.StarposMercInfo;
import com.framework.exception.RRException;
import com.framework.exception.menu.RespCode;
import com.framework.page.PageUtils;
import com.framework.redis.util.RedisUtil;
import com.framework.service.AgentService;
import com.framework.service.DeptSmsInfoService;
import com.framework.service.DeptSmsService;
import com.framework.service.DictService;
import com.framework.utils.AccountValidatorUtil;
import com.framework.utils.sms.SignSms;
import com.framework.utils.string.StringUtil;
import com.framework.validator.Assert;
import org.apache.commons.lang.StringUtils;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;

import java.io.UnsupportedEncodingException;
import java.util.Map;

/**
 * 功能描述: 短信模块
 *
 * @author ck
 * @date 2018/9/3 11:19
 */
@Service("deptSmsService")
public class DeptSmsServiceImpl extends ServiceImpl<DeptSmsDao, SysDeptSms> implements DeptSmsService {

    /**
     * 短信模板信息
     */
    @Autowired
    private DeptSmsInfoService deptSmsInfoService;

    /**
     * 字典
     */
    @Autowired
    private DictService dictService;

    @Autowired
    private RedisUtil redisUtil;
    @Autowired
    private AgentService agentService;


    @Override
    public PageUtils queryPage(Map<String, Object> params) {
        return null;
    }

    @Override
    public SysDeptSms querySmsByDeptId(Long deptId) {
        if (deptId == null || deptId == 0) {
            throw new RRException(RespCode.NOT_PARAM_ERROR);
        }
        SysDeptSms s = new SysDeptSms();
        s.setDeptId(deptId);
        s.setState(1);
        return baseMapper.selectOne(s);
    }

    @Override
    public void sendSms(String phone, String smsType, Long deptId) {
        Assert.isBlank(phone, "手机号码不能为空");
        Assert.isBlank(smsType, "短信类型不能为空");
        //注册类型
        if (StringUtils.equals("register", smsType)) {
            if (deptId == null) {
                throw new RRException("9000", "注册类型渠道为必传");
            }
            SysAgent sysAgent = agentService.queryByMobileAndDeptId(phone, deptId);

            if (sysAgent != null) {
                throw new RRException("9000", "此手机号码已经被注册");
            }
        }

        SysDeptSms sysDeptSms = querySmsByDeptId(deptId);
        if (sysDeptSms == null) {
            throw new RRException("9000", "未查询到所属渠道下的短信模板信息");
        }
        int state = sysDeptSms.getState();
        if (state == 2) {
            throw new RRException("9000", "此渠道短信已经被封禁");
        }
        SysDeptSmsInfo deptSmsInfo = deptSmsInfoService.queryDeptSmsInfo(sysDeptSms.getSmsId(), smsType);
        if (deptSmsInfo == null) {
            throw new RRException("9000", "未查询到需要发送的短信详情模板");
        }
        //查询字典中是否存在
        SysDict sysDict = dictService.querySysDict(smsType, "sms_type");
        if (sysDict == null) {
            throw new RRException("9000", "错误的短信类型");
        }
        String smsCode = StringUtil.getRandomNumberString(6);

        System.out.println("smsCode---"+smsType+"-----"+smsCode);

        //1:阿里云  2：腾讯云 3：EMA
        int type = sysDeptSms.getType();
        Map<String, Object> map = sendSmsReturnResult(phone, sysDeptSms, deptSmsInfo, smsCode, type);
        boolean success = (boolean) map.get("success");
        String message = (String) map.get("message");
        //短信发送成功
        if (success) {
            //存入短信缓存
            String value = sysDict.getValue() + phone;
            redisUtil.set(value, smsCode, RedisUtil.SMS_EXPIRATION_TIME);
        } else {
            throw new RRException("9000", message);
        }
    }

    private Map<String, Object> sendSmsReturnResult(String phone, SysDeptSms sysDeptSms, SysDeptSmsInfo deptSmsInfo, String smsCode, int type) {
        Map<String, Object> map;
        try {
            if (type == 1) {
                map = SignSms.SendALiSms(phone, smsCode, deptSmsInfo.getTeCode(), sysDeptSms.getAppId(), sysDeptSms.getAppKey(), sysDeptSms.getSignName());
            } else if (type == 3) {
                map = SignSms.sendEMASms(phone, smsCode, deptSmsInfo.getTeCode(), sysDeptSms.getAppId(), sysDeptSms.getAppKey(), sysDeptSms.getSignName());
            } else {
                map = SignSms.SendTengXunSms(phone, smsCode, deptSmsInfo.getTeCode(), sysDeptSms.getAppId(), sysDeptSms.getAppKey());
            }
        } catch (Exception e) {
            throw new RRException("9000", e.getMessage());
        }
        return map;
    }

    @Override
    public void sendYhbSms(String phone, String smsType, Long deptId) {
        Assert.isBlank(phone, "手机号码不能为空");
        Assert.isBlank(smsType, "短信类型不能为空");
        if (phone.length() != 11) {
            throw new RRException("9000", "手机号码格式不正确");
        }
        if (!AccountValidatorUtil.isMobile(phone)) {
            throw new RRException("9000", "手机号码格式不正确");
        }
        //注册类型
        if (StringUtils.equals("register", smsType)) {
            if (deptId == null) {
                throw new RRException("9000", "注册类型渠道为必传");
            }
            SysAgent sysAgent = agentService.queryByMobileAndDeptId(phone, deptId);

            if (sysAgent != null) {
                throw new RRException("9000", "此手机号码已经被注册");
            }
        }

        SysDeptSms sysDeptSms = querySmsByDeptId(deptId);
        if (sysDeptSms == null) {
            throw new RRException("9000", "未查询到所属渠道下的短信模板信息");
        }
        int state = sysDeptSms.getState();
        if (state == 2) {
            throw new RRException("9000", "此渠道短信已经被封禁");
        }
        SysDeptSmsInfo deptSmsInfo = deptSmsInfoService.queryDeptSmsInfo(sysDeptSms.getSmsId(), smsType);
        if (deptSmsInfo == null) {
            throw new RRException("9000", "未查询到需要发送的短信详情模板");
        }
        //查询字典中是否存在
        SysDict sysDict = dictService.querySysDict(smsType, "sms_type");
        if (sysDict == null) {
            throw new RRException("9000", "错误的短信类型");
        }
        String smsCode = StringUtil.getRandomNumberString(6);
        //1:阿里云  2：腾讯云 3：EMA
        int type = sysDeptSms.getType();
        Map<String, Object> map = sendSmsReturnResult(phone, sysDeptSms, deptSmsInfo, smsCode, type);
        boolean success = (boolean) map.get("success");
        String message = (String) map.get("message");
        //短信发送成功
        if (success) {
            //存入短信缓存
            String value = sysDict.getValue() + phone;
            redisUtil.set(value, smsCode, RedisUtil.SMS_EXPIRATION_TIME);
        } else {
            throw new RRException("9000", message);
        }
    }

    @Override
    public String sendCusRegResult(StarposMercInfo info, String msg) {
        SysAgent agent = agentService.queryAgentById(info.getAgentId());
        Long deptId = agent.getDeptId();
        SysDeptSms sysDeptSms = querySmsByDeptId(deptId);
        String message = "短信发送失败";
        try {
            Map<String, Object> map = SignSms.sendEMASms(info.getStoeCntTel(), "", msg, sysDeptSms.getAppId(), sysDeptSms.getAppKey(), sysDeptSms.getSignName());
            boolean success = (boolean) map.get("success");
            message = (String) map.get("message");
            if (success) {
                return "审核通过，已通知商户";
            }
        } catch (UnsupportedEncodingException e) {
            e.printStackTrace();
        }


        return message;
    }

    @Override
    public String checkSms(String smsType, String phone, String smsCode) {

        Assert.isBlank(smsType, "短信类型碧川");
        Assert.isBlank(phone, "手机号码不能为空");
        Assert.isBlank(smsCode, "验证码不能为空");

        SysDict sysDict = dictService.querySysDict(smsType, "sms_type");
        if (sysDict == null) {
            throw new RRException("9000", "错误的短信类型");
        }
        String value = sysDict.getValue() + phone;
        boolean isExist = redisUtil.hasKey(value);
        if (!isExist) {
            throw new RRException("9000", "验证码不存在或者已经失效");
        }
        String redCode = (String) redisUtil.get(value);
        if (!StringUtils.equals(smsCode, redCode)) {
            throw new RRException("9000", "验证码不正确");
        }
        return value;
    }


}
